<script setup lang="ts">
import { Setting } from '@element-plus/icons-vue'
import LineChart from './components/line-chart.vue'
import EmptyPlaceholder from './components/empty-placeholder.vue'

import LeftSettingPanel from './components/left-setting-panel.vue'
import RightSettingPanel from './components/right-setting-panel.vue'
import BottomSettingPanel from './components/bottom-setting-panel.vue'
import MiddleSettingPanel from './components/middle-setting-panel.vue'
import type { EfficiencyConfig } from './type'
import type { EquipmentClassification } from '@/types'
import { PICTURE, SPECIFICATION } from '../equipment-definition/constant'
import { EFFICIENCY_ROLE_SYMBOL } from './constant'

defineOptions({
  name: 'EquipmentEfficiency',
})

const leftPanelRef = ref<InstanceType<typeof LeftSettingPanel>>()
const rightPanelRef = ref<InstanceType<typeof RightSettingPanel>>()
const bottomPanelRef = ref<InstanceType<typeof BottomSettingPanel>>()
const middlePanelRef = ref<InstanceType<typeof MiddleSettingPanel>>()

const loading = ref(false)
const equipmentId = ref()
const equipmentList = shallowRef<{ key: string, value: string }[]>([])
const imgSrc = ref('')

const equipmentDefinitionInfo = shallowRef<EquipmentClassification[]>([])

const leftConfig = ref<EfficiencyConfig[]>([])
const rightConfig = ref<EfficiencyConfig[]>([])
const centerConfig = ref<EfficiencyConfig[]>([])
const bottomConfig = ref<EfficiencyConfig[]>([])

const leftData = ref<{ id: number, value: string, name: string }[]>([])
const rightData = ref<{ id: number, value: string, name: string }[]>([])
const centerData = ref<{ id: number, value: string, name: string }[]>([])

const bottomData = ref<{ id: number, list: { time: string, value: string }[] }[]>([])

const leftChartData = ref<{ name: string, value: string | number }[]>([])
const leftChartTitle = ref('')
const rightChartData = ref<{ name: string, value: string | number }[]>([])
const rightChartTitle = ref()

const showLeftChart = ref(false)
const showRightChart = ref(false)

// 技术参数下拉数据
const specificationOptions = computed(() => {
  return unref(equipmentDefinitionInfo).find(v => v.key === SPECIFICATION)?.list ?? []
})

// 图片信息定义信息
const picOptions = computed(() => {
  return unref(equipmentDefinitionInfo).find(v => v.key === PICTURE)?.list ?? []
})

// 左侧标题
const leftTitle = computed(() => {
  return unref(leftConfig)[0]?.title ?? ''
})

// 右侧标题
const rightTitle = computed(() => {
  return unref(rightConfig)[0]?.title ?? ''
})

async function getEquipmentList() {
  const res = await equipmentInfoApi.getEquipmentInfoList()
  equipmentList.value = res.data

  equipmentId.value = res.data[0].key
}

async function getLeftChartData(ids: number[]) {
  showLeftChart.value = false
  const res = await equipmentEfficiencyApi.queryEquipmentEfficiencyDataCurveByIds(
    ids,
  )
  leftChartData.value = res.data ? res.data[0]?.list.map(v => ({ name: v.time, value: v.value })) ?? [] : []
  showLeftChart.value = true
}

async function getRightChartData(ids: number[]) {
  showRightChart.value = false
  const res = await equipmentEfficiencyApi.queryEquipmentEfficiencyDataCurveByIds(
    ids,
  )
  rightChartData.value = res.data ? res.data[0]?.list.map(v => ({ name: v.time, value: v.value })) ?? [] : []
  showRightChart.value = true
}

function getDefinitionInfoIdForFile(actualValue: number, roleList: EfficiencyConfig['roleList']) {
  for (const item of roleList) {
    const _symbol = item.symbol
    const value = +item.value

    let symbol = EFFICIENCY_ROLE_SYMBOL.EQ
    if (actualValue < value) {
      symbol = EFFICIENCY_ROLE_SYMBOL.LT
    }
    else if (actualValue === value) {
      symbol = EFFICIENCY_ROLE_SYMBOL.EQ
    }
    else if (actualValue > value) {
      symbol = EFFICIENCY_ROLE_SYMBOL.GT
    }

    if (_symbol === symbol) {
      return item.showDefinitionInfoId
    }
  }
  return roleList[0]?.showDefinitionInfoId
}

async function getConfigs() {
  loading.value = true
  if (!unref(equipmentId))
    return
  try {
    // 配置数据
    const { data } = await equipmentEfficiencyApi.queryEquipmentEfficiencyConfigData(
      unref(equipmentId),
    )
    leftConfig.value = data.leftData ?? []
    rightConfig.value = data.rightData ?? []
    bottomConfig.value = data.downData ?? []
    centerConfig.value = data.middleData ?? []

    // 能效数据
    if (unref(leftConfig).length > 0) {
      const { data: data1 } = await equipmentEfficiencyApi.queryEquipmentEfficiencyDataByIds(
        unref(leftConfig.value.map(item => item.id)),
      )
      leftData.value = data1

      if (data1.length > 0) {
        // 左侧曲线：默认查第一个的曲线图
        getLeftChartData([data1[0].id])
        leftChartTitle.value = data1[0].name ?? ''
      }
    }
    else {
      leftData.value = []
      leftChartTitle.value = ''
    }

    if (unref(rightConfig).length > 0) {
      const { data: data2 } = await equipmentEfficiencyApi.queryEquipmentEfficiencyDataByIds(
        unref(rightConfig.value.map(item => item.id)),
      )
      rightData.value = data2
      if (data2.length > 0) {
        getRightChartData([data2[0].id])
        rightChartTitle.value = data2[0].name ?? ''
      }
    }
    else {
      rightData.value = []
      rightChartTitle.value = ''
    }

    if (unref(centerConfig).length > 0) {
      const { data: data3 } = await equipmentEfficiencyApi.queryEquipmentEfficiencyDataByIds(
        unref(centerConfig.value.map(item => item.id)),
      )
      centerData.value = data3
      // 中间数据处理
      // 将实际值与参考值对比
      const actualData = data3[0]?.value ?? 0
      // 中间状态图配置只取第一条
      const roles = centerConfig.value[0]?.roleList ?? []
      const definiitonInfoId = +getDefinitionInfoIdForFile(+actualData, roles)
      if (definiitonInfoId) {
        const { data } = await equipmentDefinitionInfoApi.queryEquipmentInfoFileById(definiitonInfoId)
        imgSrc.value = (data ?? [])[0]?.fileUrl
      }
    }
    else {
      centerData.value = []
      imgSrc.value = ''
    }

    // 曲线图数据
    if (unref(bottomConfig).length > 0) {
      const { data: data4 } = await equipmentEfficiencyApi.queryEquipmentEfficiencyDataCurveByIds(
        unref(bottomConfig.value.map(item => item.id)),
      )
      bottomData.value = data4
    }
    else {
      bottomData.value = []
    }
  }
  finally {
    loading.value = false
  }
}

// 获取设备定义信息
async function getEquipmentDefinitionInfo() {
  if (equipmentId.value) {
    const { data } = await equipmentDefinitionInfoApi.getEquipmentInfoById(equipmentId.value)
    equipmentDefinitionInfo.value = data
  }
}

async function showLeftPanel() {
  leftPanelRef.value?.open()
}
async function showRightPanel() {
  rightPanelRef.value?.open()
}
async function showBottomPanel() {
  bottomPanelRef.value?.open()
}
async function showMiddlePanel() {
  middlePanelRef.value?.open()
}

async function handleChangeLeftItem(item: any) {
  getLeftChartData([item.id])
  leftChartTitle.value = item.name
}

async function handleChangeRightItem(item: any) {
  getRightChartData([item.id])
  rightChartTitle.value = item.name
}

watch(equipmentId, async () => {
  await refresh()
})

async function refresh() {
  await getConfigs()
  await getEquipmentDefinitionInfo()
}

onMounted(() => {
  getEquipmentList()
})
</script>

<template>
  <div class="h-full w-full flex flex-col p-3 light:bg-transparent">
    <div class="relative flex flex-shrink-0 items-center justify-center">
      <ElSelect v-model="equipmentId" :clearable="false" size="large" class="text-center !w-80">
        <ElOption v-for="item in equipmentList" :key="item.key" :value="item.key" :label="item.value" />
      </ElSelect>
      <ElPopover placement="bottom" trigger="hover" :width="200">
        <template #reference>
          <div class="absolute right-4 top-1/2 cursor-pointer opacity-80 transition-all -translate-y-1/2 hover:opacity-100">
            <ElIcon :size="24">
              <Setting />
            </ElIcon>
          </div>
        </template>
        <ul class="m-0 list-none pl-0">
          <li class="cursor-pointer p-2 opacity-80 transition-all hover:opacity-100" @click="showLeftPanel()">
            左侧数据设置
          </li>
          <li class="cursor-pointer p-2 opacity-80 transition-all hover:opacity-100" @click="showRightPanel()">
            右侧数据设置
          </li>
          <li class="cursor-pointer p-2 opacity-80 transition-all hover:opacity-100" @click="showBottomPanel()">
            下侧数据设置
          </li>
          <li class="cursor-pointer p-2 opacity-80 transition-all hover:opacity-100" @click="showMiddlePanel()">
            状态图设置
          </li>
        </ul>
      </ElPopover>
    </div>
    <div class="mt-4">
      <div class="h-120 flex items-center gap-3">
        <div class="h-full flex-2/7">
          <div class="alpha-block h-[calc(50%-0.375rem)]">
            <div v-if="leftConfig.length > 0" class="h-full flex flex-col">
              <div class="mt-3 px-3">
                {{ leftTitle }}
              </div>
              <div class="flex flex-auto flex-wrap gap-3 overflow-auto p-3">
                <div
                  v-for="item in leftData" :key="item.id"
                  class="alpha-block min-w-[calc((100%-1.5rem)/3)] flex flex-1 flex-col items-center justify-center"
                  @click="handleChangeLeftItem(item)"
                >
                  <div>
                    {{ item.name }}
                  </div>
                  <p class="fs-14 mb-0 mt-1 opacity-80">
                    <code class="font-mono">{{ item.value ?? '--' }}</code>
                  </p>
                </div>
              </div>
            </div>
            <EmptyPlaceholder v-else />
          </div>
          <div class="alpha-block mt-3 h-[calc(50%-0.375rem)] min-h-200px min-w-200px">
            <LineChart v-if="leftConfig.length > 0 && showLeftChart" :data="leftChartData" :title="leftChartTitle" />
            <EmptyPlaceholder v-else />
          </div>
        </div>
        <div class="h-full flex-3/7">
          <div class="alpha-block h-full w-full flex items-center justify-center">
            <ElImage :src="imgSrc" alt="1.png" class="h-full w-full" fit="cover">
              <template #error>
                <EmptyPlaceholder />
              </template>
            </ElImage>
          </div>
        </div>
        <div class="h-full flex-2/7">
          <div class="alpha-block h-[calc(50%-0.375rem)]">
            <div v-if="rightConfig.length > 0" class="h-full flex flex-col">
              <div class="mt-3 px-3">
                {{ rightTitle }}
              </div>
              <div class="flex flex-auto flex-col gap-3 overflow-auto p-3">
                <div v-for="item in rightData" :Key="item.id" class="alpha-block flex flex-auto flex-col items-center justify-center py-2" @click="handleChangeRightItem(item)">
                  <div>{{ item.name }}</div>
                  <p class="fs-14 mb-0 mt-1 opacity-80">
                    <code class="font-mono">{{ item.value ?? '--' }}</code>
                  </p>
                </div>
              </div>
            </div>
            <EmptyPlaceholder v-else />
          </div>
          <div class="alpha-block mt-3 h-[calc(50%-0.375rem)] min-h-200px min-w-200px w-full">
            <LineChart v-if="rightConfig.length > 0 && showRightChart" :data="rightChartData" :title="rightChartTitle" color="#A0FF9E" />
            <EmptyPlaceholder v-else />
          </div>
        </div>
      </div>
    </div>
    <div v-memo="[bottomData]" class="mt-3 flex-auto overflow-auto">
      <div v-if="bottomConfig.length > 0" class="h-full w-full flex items-center gap-3">
        <div v-for="(item, index) in bottomData" :key="item.id" class="alpha-block h-full min-w-[calc((100%-1.5rem)/3)] w-full flex-auto">
          <LineChart :data="item.list.map(v => ({ name: v.time, value: v.value }))" :title="bottomConfig[index]?.dataName ?? ''" :color="['#64B5F6', '#81C784', '#BA68C8'][index]" />
        </div>
      </div>
      <div v-else class="alpha-block h-full w-full">
        <EmptyPlaceholder />
      </div>
    </div>

    <LeftSettingPanel
      v-if="equipmentId"
      ref="leftPanelRef" :options="specificationOptions"
      :equipment-id="equipmentId"
      :old-list="leftConfig"
      @save-success="refresh"
    />
    <RightSettingPanel
      v-if="equipmentId"
      ref="rightPanelRef"
      :equipment-id="equipmentId"
      :old-list="rightConfig"
      @save-success="refresh"
    />
    <BottomSettingPanel
      v-if="equipmentId"
      ref="bottomPanelRef"
      :equipment-id="equipmentId"
      :old-list="bottomConfig"
      @save-success="refresh"
    />
    <MiddleSettingPanel
      v-if="equipmentId"
      ref="middlePanelRef"
      :equipment-id="equipmentId"
      :old-list="centerConfig"
      :attachment-definitions="picOptions"
      @save-success="refresh"
    />
  </div>
</template>

<style>
.text-center .el-select__wrapper {
  text-align: center !important;
}
</style>
